﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TimerTest
{
    class TimerUtil
    {
        private class StateObjClass
        {
            public int SomeValue;
            public System.Threading.Timer TimerReference;
            public bool TimerCanceled;
        }

        public void RunTimer()
        {
            StateObjClass stateObj = new StateObjClass();

            stateObj.SomeValue = 0;

            stateObj.TimerCanceled = false;

            TimerCallback timerCallback = new TimerCallback(TimerTask);

            Timer timer = new Timer(timerCallback, stateObj, 2000, 2000);

            // Save a reference for Dispose.
            stateObj.TimerReference = timer;

            // Run for ten loops.
            while (stateObj.SomeValue < 10)
            {
                // Wait one second.
                System.Threading.Thread.Sleep(1000);
            }

            // Request Dispose of the timer object.
            stateObj.TimerCanceled = true;

            Console.ReadKey();

        }

        private void TimerTask(object state)
        {
            StateObjClass stateObjClass = (StateObjClass)state;
            System.Threading.Interlocked.Increment(ref stateObjClass.SomeValue);
            Console.WriteLine("Launched new thread  " + DateTime.Now.ToString());
            if (stateObjClass.TimerCanceled)
            // Dispose Requested.
            {
                stateObjClass.TimerReference.Dispose();
                Console.WriteLine("Done  " + DateTime.Now.ToString());
            }
        }
    }
}
